﻿<template>
  <div class="app-container">
    <div class="chart-title with-back">
      <div class="chart-left">
        <div>档案管理</div>
        <div class="backtrack">
          <el-button @click="comeBack">返回</el-button>
        </div>
      </div>
    </div>
    <div class="info-items">
      <div class="info-title">基本信息</div>
      <div>
        <el-form
          ref="baseForm"
          :rules="baseRules"
          :model="base"
          label-position="right"
          label-width="150px"
          size="small"
        >
          <div class="base-from">
            <div class="base-items">
              <el-form-item
                :label="$t('delivery.company')+':'"
                prop="name"
              >
                <el-input
                  v-model="base.name"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </div>
            <div class="base-items">
              <el-form-item
                :label="$t('public.mobile')+':'"
                prop="mobile"
              >
                <el-input
                  v-model="base.mobile"
                  :readonly="dialogStatus === 'edit' ? false:true"
                ></el-input>
              </el-form-item>
            </div>
            <div class="base-items">
              <el-form-item :label="$t('public.creationTime')">
                <el-input
                  v-model="base.create_time"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    <div class="nav-bar"></div>
    <div class="info-items special">
      <div class="special-content">
        <div class="info-content">
          <div class="info-title">绑定人员</div>
          <div
            class="new-staff"
            @click="handleCreate"
          >
            <div class="add-buttom">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="add-name">新建人员</div>
          </div>
        </div>
        <el-table
          :data="staffOptions"
          border
          :header-cell-style="{background:'#F2F1F6',color:'#8B94BE'}"
          style="width: 100%"
        >
          <el-table-column
            fixed="left"
            align="center"
            :label="$t('table.id')"
            width="65"
          >
            <template slot-scope="scope">
              <span>{{
                  (listQuery.page - 1) * listQuery.limit + scope.$index + 1
                }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.mobile')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.mobile }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.status')"
          >
            <template slot-scope="scope">
              <span>{{ bindStatus(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.bind')"
          >
            <template slot-scope="scope">
              <div
                class="band-button"
                @click="handleBind(scope.row)"
                v-text="scope.row.status === 0?'绑定':'解绑'"
              ></div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.actions')"
            class-name="operat-button"
            fixed="right"
          >
            <template slot-scope="scope">
              <div
                class="read-img"
                @click="handleModifyStatus(scope.row, 'deleted')"
              >
                <img src="@/assets/images/delete@2x.png" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="operat-content">
        <div>
          <div
            class="operat-edit"
            @click="handleEdit"
            v-if="dialogStatus !== 'edit'"
          >编辑</div>
        </div>
        <div class="operat-verify">
          <div
            class="operat-cancel"
            v-if="dialogStatus === 'edit'"
            @click="cancelData"
          >取消</div>
          <div
            class="operat-confirm"
            @click="updateData"
            v-if="dialogStatus === 'edit'"
          >确定</div>
        </div>
      </div>
    </div>
    <!-- 编辑 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        size="small"
      >
        <div class="pops">
          <div class="pops-normal">
            <el-form-item
              :label="$t('public.name')"
              prop="name"
            >
              <el-input
                v-model="temp.name"
                :readonly="dialogStatus !== 'create' ? true : false"
              ></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('public.mobile')"
              prop="mobile"
            >
              <el-input
                v-model="temp.mobile"
                :readonly="dialogStatus !== 'create' ? true : false"
              ></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">{{
              $t("table.cancel")
            }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          :disabled="!createDisabled"
          @click="createData"
        >{{ $t("table.confirm") }}</el-button>
        <el-button
          v-else
          type="primary"
          @click="dialogFormVisible = false"
        >{{ $t("table.confirm") }}</el-button>
      </div>
    </el-dialog>
    <!-- 绑定 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogVisible"
    >
      <div class="QR-img">
        <img :src="QRCode" />
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">{{
              $t("table.cancel")
            }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          :disabled="!createDisabled"
          @click="createData"
        >{{ $t("table.confirm") }}</el-button>
        <el-button
          v-else
          type="primary"
          @click="dialogVisible = false"
        >{{ $t("table.confirm") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie
var QRCode = require("qrcode");
export default {
  name: "IsupplierProfile",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    const validateLinkmanMobile = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        var reg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/; /* 定义验证表达式 */
        if (reg.test(value)) {
          /* 进行验证 */
          callback();
        } else {
          callback(new Error("请输入正确的联系电话"));
        }
      } else {
        callback(new Error("请填写联系电话"));
      }
    };
    return {
      tableKey: 0,
      list: null,
      staffOptions: [],
      total: null,
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        linkman: "",
        linkman_mobile: "",
        region_name: "",
        type: undefined
      },
      QRCode: "",
      dispatching_id: undefined,
      base: {
        id: undefined,
        name: "",
        mobile: "",
        create_time: "",
        is_delete: undefined,
        people_count: ""
      },
      temp: {
        id: undefined,
        mobile: ""
      },
      dialogFormVisible: false,
      dialogVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看",
        bind: "绑定"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: validateName }],
        itoc_id: [{ required: true, message: "请选择运营中心", trigger: "change" }],
        address: [{ required: true, message: "请填写地址", trigger: "change" }]
      },
      baseRules: {
        linkman: [{ required: true, message: "请填写联系人", trigger: "change" }],
        linkman_mobile: [{ required: true, trigger: "blur", validator: validateLinkmanMobile }],
        dispatching_id: [{ required: true, message: "请选择配送员", trigger: "change" }]
      },
      createDisabled: true,
      updateDisabled: true,
      pageSize: 20
    };
  },
  created() {
    const token = getToken();
    if (
      token &&
      !this.$store.state.socket.loginTransition &&
      !this.$store.state.socket.loginAccount
    ) {
      this.tokenLogin(token);
    }
    this.dispatching_id = this.$route.query.id;
    this.getList();
    this.employeeList()
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    // 获取配送公司信息
    getList() {
      const path = {
        app: "archives",
        api: "api_archives_dispatching_getList",
        version: "1.0",
        type: 1,
        data: {
          id: this.dispatching_id || ''
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 获取该配送公司下的员工列表
    employeeList() {
      const path = {
        app: "archives",
        api: "api_archives_dispatching_getStaffList",
        version: "1.0",
        type: 2,
        data: {
          dispatching_id: this.dispatching_id || ""
        }
      }
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleEdit() {
      this.dialogStatus = "edit";
      this.$nextTick(() => {
        this.$refs["baseForm"].clearValidate();
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        mobile: ""
      };
    },
    // 添加供货商职员
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            const path = {
              app: "archives",
              api: "api_archives_dispatching_addStaff",
              version: "1.0",
              type: 2,
              data: {
                dispatching_id: this.dispatching_id ? this.dispatching_id : "",
                name: this.temp.name ? this.temp.name : "",
                mobile: this.temp.mobile ? this.temp.mobile : ""
              }
            }
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    // 更新供货商档案
    updateData() {
      this.$refs["baseForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const path = {
              app: "archives",
              api: "api_archives_dispatching_edit",
              version: "1.0",
              type: 2,
              data: {
                id: this.dispatching_id ? this.dispatching_id : "",
                mobile: this.base.mobile ? this.base.mobile : ""
              }
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    //  取消更新供应商
    cancelData() {
      this.dialogStatus = 'read'
      this.getList();
    },
    // 微信绑定/解绑
    handleBind(row) {
      console.log('微信绑定', row)
      if (row.status === 1) {
        const path = {
          app: "wx",
          api: "api_wx_pc_cancel",
          version: "1.0",
          type: 1,
          data: {
            id: row.id,
            account_type: 6,
            openid: row.openid
          }
        }
        console.log('JSON.stringify(path)', JSON.stringify(path))
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
        });
      } else {
        const path = {
          app: "wx",
          api: "api_wx_pc_getBindingCode",
          version: "1.0",
          type: 1,
          data: {
            id: row.id,
            account_type: 6
          }
        }
        this.socketApi.sendSock(JSON.stringify(path), res => {
          this.socketData(res);
        });
      }
    },
    getQRCodeImg(weChatUrl) {
      let QRurl = "";
      if (weChatUrl) {
        QRCode.toDataURL(weChatUrl, function(err, url) {
          if (err) {
            QRurl = "";
          } else {
            QRurl = url;
          }
        });
      } else {
        QRurl = "";
      }
      this.QRCode = QRurl;
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该职员信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const path = {
            app: "archives",
            api: "api_archives_dispatching_deleteStaff",
            version: "1.0",
            type: 2,
            data: {
              id: row.id
            }
          };
          this.socketApi.sendSock(JSON.stringify(path), res => {
            if (res) {
              this.socketData(res);
            } else {
              this.$message.error(" 删除失败 ");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    choose(data, name) {
      if (name === "distr") {
        this.base.dispatching_id = data.id;
        this.base.dispatching_name = data.name;
      }
      this.calibration("baseForm");
    },
    remove(name) {
      if (name === "distr") {
        this.base.dispatching_id = undefined;
        this.base.dispatching_name = "";
      }
      this.calibration("baseForm");
    },
    socketData(res) {
      console.log('res', res)
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            });
          } else if (resj.api === "api_archives_dispatching_getList") {
            if (resj.data[0]) {
              this.base = Object.assign({}, resj.data[0]);
            }
          } else if (resj.api === "api_archives_dispatching_getStaffList") {
            this.staffOptions = resj.data
          } else if (resj.api === "api_archives_dispatching_edit") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
            this.dialogStatus = 'read'
            this.getList();
          } else if (resj.api === "api_archives_dispatching_deleteStaff") {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.employeeList(this.dispatching_id);
          } else if (resj.api === "api_archives_dispatching_addStaff") {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.employeeList(this.dispatching_id);
          } else if (resj.api === "api_wx_pc_cancel") {
            this.$notify({
              title: "成功",
              message: "解绑成功",
              type: "success",
              duration: 2000
            });
            this.employeeList()
          } else if (resj.api === "api_wx_pc_getBindingCode") {
            this.getQRCodeImg(resj.data.url)
            this.dialogStatus = 'bind';
            this.dialogVisible = true;
          } else if (resj.api === "api_wx_pc_bindingSuccess") {
            this.$notify({
              title: "成功",
              message: "綁定成功",
              type: "success",
              duration: 2000
            });
            this.dialogVisible = false;
            this.employeeList()
          }
        }
      }
    },
    calibration(name) {
      this.$refs[name].validate(valid => { });
    },
    comeBack() {
      this.$router.push({ path: '/base-data/shipper-profile' })
    }
  }
};
</script>
<style scoped>
.info-items {
  padding: 16px;
  background-color: #ffffff;
  box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
.info-items.special {
  padding: 0;
}
.special-content {
  padding: 16px;
}
.base-from {
  display: flex;
}
.base-from .base-items {
  flex: 1;
}
.nav-bar {
  height: 8px;
  background: rgba(240, 242, 245, 1);
}
.info-title {
  margin-bottom: 16px;
  line-height: 1;
}
.info-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.add-buttom {
  display: flex;
  align-items: center;
}
.new-staff {
  display: flex;
  align-items: center;
}
.new-staff:hover .el-icon-circle-plus,
.new-staff:hover .add-name {
  display: flex;
  align-items: center;
  color: #2d67e8;
}
.add-name {
  line-height: 1;
  margin-left: 8px;
}
.band-button {
  width: 64px;
  height: 32px;
  background: rgba(228, 234, 248, 1);
  border-radius: 16px;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
  line-height: 1;
}
.operat-content {
  margin-top: 40px;
  border-top: 1px solid #e0e0e0;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
}
.operat-edit {
  width: 72px;
  height: 32px;
  background: rgba(227, 235, 255, 1);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(45, 102, 231, 1);
}
.operat-verify {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.operat-cancel {
  width: 72px;
  height: 32px;
  background: rgba(241, 242, 246, 1);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(153, 153, 153, 1);
}
.operat-confirm {
  margin-left: 24px;
  width: 72px;
  height: 32px;
  background: rgba(45, 65, 152, 1);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
}
.QR-img {
  text-align: center;
}
</style>
